package com.server;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GetCourseInfos extends HttpServlet {
	/**
	 * 获取教师的所有课程
	 * 接收tid
	 * 查询数据库
	 * 返回:
	 * jsonArray:
	 * 		jsonObject:
	 * 			course_name
	 * 			cid
	 * 			times
	 */
	private String tid;
	private JsonArray jsonArray;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		tid = request.getParameter("tid");

		//数据库获取课程信息
		if(tid != null && !tid.equals("")){
			String sql = "SELECT courses.cid,course_name,time_count FROM courses,teacher_course WHERE courses.cid = teacher_course.cid and tid = "+tid+";";
			DBTools db = new DBTools();
			ResultSet rs = db.query(sql);

			//json填充
			jsonArray = new JsonArray();
			try {
				while (rs.next()) {
					JsonObject jsonObject = new JsonObject();
					jsonObject.addProperty("cid", rs.getString("courses.cid"));
					jsonObject.addProperty("course_name", rs.getString("course_name"));
					jsonObject.addProperty("time_count", rs.getInt("time_count"));
					jsonArray.add(jsonObject);
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				db.close();
			}
		}

		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		out.write(jsonArray.toString());
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 *
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
